const express = require('express');
const router = express.Router();
const { readExcelFile, searchExcelData } = require('../utils/excelReader');

// Get all data from Excel file
router.get('/data', async (req, res) => {
    try {
        const data = await readExcelFile();
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Search data in Excel file
router.get('/search', async (req, res) => {
    try {
        const { query } = req.query;
        
        if (!query) {
            return res.status(400).json({ error: 'Search query is required' });
        }

        const results = await searchExcelData(query);
        res.json(results);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Get detail by ID
router.get('/detail/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const data = await readExcelFile();
        const detail = data.find(item => item.id === id || item.ISBN === id);
        
        if (!detail) {
            return res.status(404).json({ error: 'Record not found' });
        }
        
        res.json(detail);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;
